<template>
	<view class="bg-white">
		<cu-custom :bgColor="globalData.bgColor" :isBack="true">
			<template #content>
				<text class="text-darkgrey">{{ $t('home.shop-home.fah548') }}</text>
			</template>
		</cu-custom>
		<view class="search">
			<view class="flex bg-white padding-tb-sm solid-bottom">
				<view class="search-content round">
					<text class="cuIcon-search padding-right-xs margin-left"></text>
					<input type="text" :placeholder="$t('order.list.58345j')" v-model="inputKey"
						confirm-type="search" />
				</view>
				<view class="action">
					<button class="cu-btn bg-blue round search-button margin-right-sm"
						@click="search">{{ $t('bargain.bargainuser.655110') }}</button>
				</view>
			</view>
			<scroll-view scroll-x class="bg-white nav solid-bottom">
				<view class="cu-item flex-sub" :class="index == TabCur ? 'text-blue cur' : ''"
					v-for="(item, index) in tabs" :key="index" @tap="tabSelect" :data-id="index">
					{{ item }}
				</view>
			</scroll-view>
		</view>
		<view style="margin-top: 190rpx">
			<mescroll-body class="bg-gray" ref="mescrollRef" :down="downOption" :up="upOption" @init="mescrollInit"
				@down="downCallback" @up="upCallback">
				<view class="cu-list">
					<view class="cu-item radius bg-white solid-bottom" v-for="data in dataList" :key="data.id">
						<!-- 待发货 -->
						<div class="send-title padding-left-sm padding-top">{{data.statusDesc}}</div>
						<div v-if="data?.statusDesc === '待发货'" class="padding-left-sm padding-top send-limit">
							距<text>24h</text>发货剩余:<text class="send-time">{{getTimeLeft(data.paymentTime)}}</text></div>

						<view class="flex justify-between">
							<view class="padding-top padding-left-sm padding-bottom-sm">
								<text
									class="text-darkgrey text-sm cuIcon-titles">{{ $t('goodsappraises.list.k1h88u') }}{{ data.orderNo }}</text>
							</view>
						</view>
						<div v-if="data?.statusDesc === '待发货'" class="send-line"></div>
						<div class="text padding-left-sm text-black" v-if="data?.statusDesc === '待发货'">
							1种商品,共{{data?.listOrderItem?.length || 0}}件</div>
						<view class="cu-list menu-avatar flex justify-between padding-left align-center"
							v-for="item in data.listOrderItem" :key="item.id">
							<view class="cu-avatar img-box bg-white"
								:style="{ 'background-image': item.picUrl ? 'url(' + item.picUrl + ')' : '' }"></view>
							<view class="content flex-sub padding-lr">
								<view class="text-darkgrey text-lg text-bold text-to-long">
									<text v-if="data.orderType != '0'"
										class="cu-tag text-sm light bg-red margin-right-xs radius">
										{{
											data.orderType == '1'
												? $t('order.detail.73mq07')
												: data.orderType == '2'
												? $t('order.detail.6kcy5i')
												: data.orderType == '3'
												? $t('order.detail.4m2y04')
												: ''
										}}
									</text>
									{{ item.spuName }}
								</view>
								<view class="text-darkgrey text-df flex justify-between margin-top-xs text-sm">
									<text>{{ $t('goodsappraises.list.5n08pj') }}{{ item.specInfo ? item.specInfo : $t('order.detail.44038b') }}</text>
									<text>×{{ item.quantity }}</text>
								</view>
								<view class="margin-top-xs justify-between">
									<view class="cu-tab line-orange sm margin-top-xs text-sm">{{ item.statusDesc }}
									</view>
									<view class="text-darkgrey text-sm">
										{{ $t('order.detail.287ftg') }}
										<text class="text-red text text-price">
											{{ item.paymentPrice }}
											<text
												v-if="item.paymentCouponPrice">{{ ' +' + $t('order.detail.8mlu0h') + item.paymentCouponPrice }}</text>
											{{ item.paymentPoints ? $t('order.detail.fhg1r7') + item.paymentPoints : '' }}
										</text>
										<text class="text-blue margin-left-xl" @click="showEditPriceDialog(item)"
											v-if="item.status == '0' && data.isPay == '0' && !data.status">
											{{ $t('order.detail.7b7y07') }}
											<text class="cuIcon-write"></text>
										</text>
									</view>
								</view>
							</view>
						</view>
						<view class="padding-lr text-sm margin-top" v-if="data.orderLogistics">
							<view class="text-purple-grey">
								<text class="text-purple-grey cuIcon-deliver margin-right-xs"></text>
								{{ data.deliveryWay == 1 ? $t('order.detail.50tob3') : $t('order.list.5j446b') }}
							</view>
							<view v-if="data.deliveryWay == 1" class="margin-top-xs">
								<!-- <view class="text-lg text-black ">收货人信息</view> -->
								<view class="text-purple-grey margin-top-xs">
									<text class="text-purple-grey cuIcon-people margin-right-xs"></text>
									{{ data.orderLogistics.userName + ' ' }}{{ data.orderLogistics.telNum }}
								</view>
								<view class="margin-top-xs text-purple-grey">
									<text class="text-purple-grey cuIcon-location margin-right-xs"></text>
									{{ data.orderLogistics.address }}
								</view>
								<view class="margin-top-xs text-purple-grey">
									<text class="text-purple-grey cuIcon-time margin-right-xs"></text>
									{{ data.createTime }}
								</view>
							</view>
						</view>
						<view class="padding-left padding-right text-sm margin-top-xs padding-bottom-xs">
							<view class="text-df text-purple-grey margin-bottom-xs text-sm"
								v-if="data.orderLogistics && data.orderLogistics.message">
								<text class="text-sm">{{ $t('order.detail.ers335') }}</text>
								<text class="text-sm">{{ data.orderLogistics.message }}</text>
							</view>
							<view class="text-df text-black flex justify-between">
								<view class="text-darkgrey">
									{{ $t('order.detail.4382fy') }}
									<text
										class="text-price text-xl text-bold text-red margin-right-xs">{{ data.paymentPrice }}</text>
									<text class="text-purple-grey text-sm">{{ $t('order.list.2we9w6') }}</text>
								</view>
								<!-- <view class="text-sm text-gray padding-top-xs">{{data.createTime}}</view> -->
							</view>
							<div v-if="data?.statusDesc === '待发货'" class="send-line1"></div>

							<view class="flex margin-top-xs">
								<view class="text-xs margin-right-xs light round pay" v-if="data.appraisesStatus"
									:class="data.appraisesStatus != 0 ? 'bg-blue' : 'bg-orange'">
									{{
										data.appraisesStatus == '0'
											? $t('order.detail.k6x6s1')
											: data.appraisesStatus == '1'
											? $t('order.detail.l2kk8z')
											: data.appraisesStatus == '2'
											? $t('order.detail.4ex3n0')
											: ''
									}}
								</view>
								<view class="text-xs margin-right-xs light round pay"
									:class="data.isPay == 1 ? 'bg-cyan' : 'bg-orange'">
									{{ data.isPay == 1 ? $t('order.detail.4y6774') : $t('order.detail.uxo96u') }}
								</view>
								<view class="text-xs margin-right-xs light round pay"
									:class="data.status == 2 || data.status == 3 || data.status == 4 ? 'bg-blue' : 'bg-orange'">
									{{ data.statusDesc }}
								</view>
							</view>
						</view>
						<div v-if="data?.statusDesc === '待发货'" class="send-line1"></div>
						<div class="send-address-info padding-left" v-if="data?.statusDesc === '待发货'">
							<div class="sai-header">
								<div class="sai-name">{{maskName(data.recName)}}</div>
								<div class="sai-phone">{{maskPhone(data.recTel)}}</div>
							</div>
							<div class="sai-detail">
								{{ data.showFull ? data.recAddress : maskAddress(data.recAddress) }}
								<img v-if="data.showFull" @click="data.showFull = !data.showFull"
									src="https://hqtsc.oss-cn-beijing.aliyuncs.com/1/material/12bc64ac-a241-45fa-a7e4-5df26faa5723.png"
									alt="">
								<img v-else @click="data.showFull = !data.showFull"
									src="https://hqtsc.oss-cn-beijing.aliyuncs.com/1/material/076e2390-baa5-4b37-8ee9-4e490ddbd832.png"
									alt="">
							</div>
						</div>

						<view
							class="flex justify-between align-center padding-left padding-right margin-top-xs padding-bottom-sm text-sm">
							<!-- 							<view>
								<text class="cuIcon-time margin-right-xs"></text>
								{{ data.createTime }}
							</view> -->
							<view>
								<text class="margin-right-xs"></text>
							</view>
							<view v-if="globalData.permissions['mall:orderinfo:edit']" class="flex justify-end">
								<view v-if="data.isPay == '0' && !data.status"
									class="cu-btn round bg-blue button-bg margin-right-sm" @tap="onOrderCancel(data)">
									取消订单
								</view>
								<view v-if="data.status == 1 && data.deliveryWay == 2"
									class="cu-btn round bg-blue button-bg margin-right-sm" @tap="onTakeGoods(data)">
									{{ $t('order.detail.bxsq86') }}
								</view>
								<navigator :url="'logisticsForm?id=' + data.id" v-else-if="data.status == 1"
									class="cu-btn round button-bg bg-blue shadow-blur margin-right-sm">
									{{ $t('order.detail.o7cmyd') }}
								</navigator>
								<navigator :url="'detail?id=' + data.id"
									class="cu-btn round bg-blue button-bg margin-right-sm">
									{{ $t('bargain.bargainuser.f60nm4') }}
								</navigator>
								<navigator :url="'detail?id=' + data.id" class="cu-btn round bg-orange button-bg">
									添加备注
								</navigator>
							</view>
							<view v-else class="flex justify-end">
								<navigator :url="'detail?id=' + data.id" class="cu-btn round bg-blue button-bg">
									{{ $t('bargain.bargainuser.f60nm4') }}
								</navigator>
							</view>
						</view>
					</view>
				</view>
			</mescroll-body>
		</view>
		<!-- 改价弹框 -->
		<view class="cu-modal" :class="showModal ? 'show' : ''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">{{ $t('order.detail.x27ebr') }}</view>
					<view class="action" @tap="showModal = false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding">
					<input :placeholder="$t('order.detail.ajn4t3')" type="number" name="paymentPrice"
						v-model="editPriceForm.paymentPrice" />
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green"
							@tap="showModal = false">{{ $t('login.login.5csq28') }}</button>
						<button class="cu-btn bg-green margin-left"
							@tap="handleEditPrice">{{ $t('goodsappraises.list.6to1i8') }}</button>
					</view>
				</view>
			</view>
		</view>
		<!-- 扫码核销 -->
		<float-btn @onFloatBtnClick="onTips" icon="cuIcon-question" :bottom="310"></float-btn>
		<float-btn @onFloatBtnClick="onScan('pad')" icon="cuIcon-scan"></float-btn>

		<!-- #ifdef H5 -->
		<view class="cu-modal" :class="showScanModal ? ' show' : ''" @tap="showScanModal = false">
			<view v-if="showScanModal" class="cu-dialog bg-white" @tap.stop>
				<view class="cu-bar justify-end">
					<view class="content">扫码</view>
					<view class="action" @tap="showScanModal = false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view style="height: 50vh" class="flex justify-center align-center">
					<mumu-get-qrcode @success="qrcodeSucess" @error="qrcodeError"></mumu-get-qrcode>
				</view>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import floatBtn from '@/components/basic-components/float-btn/index.vue';
	// 引入mescroll-mixins.js
	import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';

	import {
		getPage,
		takeGoods,
		orderCancel,
		editPrice
	} from '@/api/mall/orderinfo';

	import permision from '@/public/app-plus/permission.js';
	// #ifdef H5
	// H5二维码扫码
	import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue';
	// #endif

	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			floatBtn,
			// #ifdef H5
			mumuGetQrcode
			// #endif
		},
		onLoad(e) {
			if (e && e.status) {
				this.TabCur = Number(e.status) + 1;
				this.scrollLeft = (this.TabCur - 1) * 60;
			}
		},
		onShow() {
			if (this.mescroll) {
				this.mescroll.resetUpScroll(); //刷新
			}
		},
		data() {
			return {
				globalData: getApp().globalData,
				CustomBar: this.CustomBar,
				TabCur: 0,
				scrollLeft: 0,
				tabs: [
					this.$t('order.list.qp8mo2'),
					this.$t('home.index.88oddj'),
					this.$t('home.index.28g45r'),
					this.$t('home.index.7q2j52'),
					this.$t('groupon.grouponuser.mql526'),
					this.$t('order.list.78438g'),
					this.$t('order.list.805s64')
				],
				inputKey: '',
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				downOption: {
					// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: this.$t('bargain.bargaininfo.m3k7oc')
					}
				},
				// 列表数据
				dataList: [],
				showModal: false,
				editPriceForm: {
					id: null,
					paymentPrice: 0
				},
				showScanModal: false //h5扫码
			};
		},
		onPageScroll(e) {
			uni.$emit('onPageScroll', e);
		},
		methods: {
			maskName(name) {
				if (!name || typeof name !== 'string') return '';
				const len = name.length;
				if (len === 1) return name;
				if (len === 2) return name[0] + '*';
				return name[0] + '*'.repeat(len - 2) + name[len - 1];
			},
			maskPhone(phone) {
				if (!phone || typeof phone !== 'string' || phone.length < 7) return phone;
				return phone.slice(0, 3) + '****' + phone.slice(-4);
			},
			maskAddress(address) {
				if (typeof address !== 'string' || !address.trim()) return '';
				return address.replace(/\d/g, '*');
			},
			getTimeLeft(payTimeStr) { // 距离24h发货剩余 hh:mm:ss
				const payTime = new Date(payTimeStr);
				const deadline = new Date(payTime.getTime() + 24 * 60 * 60 * 1000);
				const now = new Date();

				let diff = deadline - now;
				if (diff <= 0) return '00:00:00';

				const hours = Math.floor(diff / (1000 * 60 * 60));
				const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
				const seconds = Math.floor((diff % (1000 * 60)) / 1000);

				const pad = n => n.toString().padStart(2, '0');
				return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
			},
			showEditPriceDialog(item) {
				this.editPriceForm.id = item.id;
				this.editPriceForm.paymentPrice = item.paymentPrice;
				this.showModal = true;
			},
			//改价
			handleEditPrice() {
				if (!this.editPriceForm.paymentPrice) {
					uni.showToast({
						title: this.$t('order.detail.43u8c1'),
						icon: 'none'
					});
					return;
				}
				editPrice({
						id: this.editPriceForm.id,
						paymentPrice: this.editPriceForm.paymentPrice
					})
					.then((data) => {
						uni.showToast({
							title: this.$t('order.detail.m6f5u2')
						});
						this.mescroll.resetUpScroll(); //刷新
						this.showModal = false;
					})
					.catch(() => {});
			},
			//订单取消
			onOrderCancel(row, index) {
				var _this = this;
				uni.showModal({
					title: this.$t('bargain.bargaininfo.b8740a'),
					content: this.$t('order.detail.53vu17'),
					success: (res) => {
						if (res.confirm) {
							orderCancel(data.id)
								.then((data) => {
									uni.showToast({
										title: this.$t('order.detail.jx810q')
									});
									_this.mescroll.resetUpScroll(); //刷新
								})
								.catch(function(err) {});
						} else if (res.cancel) {}
					}
				});
			},
			//提货
			onTakeGoods(data) {
				var _this = this;
				uni.showModal({
					title: this.$t('bargain.bargaininfo.b8740a'),
					content: this.$t('order.detail.ux6f1y'),
					success: (res) => {
						if (res.confirm) {
							takeGoods(data.id)
								.then((data) => {
									uni.showToast({
										title: this.$t('order.detail.h41m2m')
									});
									_this.mescroll.resetUpScroll(); //刷新
								})
								.catch(function(err) {});
						} else if (res.cancel) {}
					}
				});
			},
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				this.mescroll.resetUpScroll();
			},
			search(val) {
				this.mescroll.resetUpScroll();
			},
			/*mescroll组件初始化的回调,可获取到mescroll对象 (此处可删,mixins已默认)*/
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调, 有三种处理方式:*/
			downCallback() {
				this.mescroll.resetUpScroll(); // 重置列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
				this.mescroll.endSuccess();
			},
			/*上拉加载的回调*/
			upCallback(page) {
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				let querySearch = '?current=' + pageNum + '&size=' + pageSize + '&descs=create_time';
				if (this.inputKey) {
					querySearch = querySearch + '&orderNo=' + this.inputKey;
				}
				if (this.TabCur > 0) {
					querySearch = querySearch + '&status=' + (this.TabCur - 1);
				}
				getPage(querySearch).then((response) => {
					if (response.data) {
						// 接口返回的当前页数据列表 (数组)
						let curPageData = response.data.records;
						// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
						let curPageLen = curPageData.length;
						// 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)
						let totalSize = response.data.total;
						//设置列表数据
						if (page.num == 1) this.dataList = []; //如果是第一页需手动置空列表
						this.dataList = this.dataList.concat(curPageData); //追加新数据
						// 请求成功,隐藏加载状态
						this.mescroll.endBySize(curPageLen, totalSize);
						setTimeout(() => {
							this.mescroll.endSuccess(curPageLen);
						}, 20);
					}
				});
			},
			onTips() {
				uni.showModal({
					title: this.$t('bargain.bargaininfo.b8740a'),
					content: this.$t('order.list.921c29'),
					showCancel: false,
					confirmText: this.$t('order.list.f079tc'),
					success: (res) => {}
				});
			},
			scanSuccess(res) {
				// 扫码成功
				if (res) {
					uni.navigateTo({
						url: '/pages/mall/order/detail?id=' + res
					});
				} else {
					uni.showToast({
						title: this.$t('order.list.zq5k2i'),
						icon: 'none'
					});
				}
			},
			async checkPermission(code) {
				let status = permision.isIOS ? await permision.requestIOS('camera') : await permision.requestAndroid(
					'android.permission.CAMERA');
				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: this.$t('order.list.xr3974'),
						confirmText: this.$t('order.list.ei61mf'),
						success: (res) => {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					});
				}
				return status;
			},
			async onScan(model = 'pad') {
				// #ifdef H5
				this.onScanH5();
				// #endif
				// #ifndef H5
				// #ifdef APP
				let status = await this.checkPermission();
				if (status !== 1) {
					return;
				}
				// #endif
				let that = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					onlyFromCamera: true,
					success: (res) => {
						// console.log("res: " + JSON.stringify(res));
						that.scanSuccess(res.result);
					},
					fail: (err) => {}
				});
				// #endif
			},
			onScanH5(to) {
				this.showScanModal = true;
			},
			qrcodeSucess(data) {
				this.scanSuccess(data);
			},
			qrcodeError(err) {
				console.log(err);
				uni.showModal({
					title: '摄像头授权失败',
					content: '摄像头授权失败，请检测当前浏览器是否有摄像头权限。',
					success: () => {}
				});
			}
		}
	};
</script>

<style>
	.search {
		width: 100%;
		padding-bottom: 20rpx;
		position: fixed;
		z-index: 999;
	}

	.search-content {
		background-color: #f5f5f5;
		line-height: 64upx;
		height: 64upx;
		font-size: 24upx;
		color: #333333;
		flex: 1;
		display: flex;
		align-items: center;
		margin: 0 30upx;
	}

	.search-content input {
		flex: 1;
		padding-right: 30upx;
		height: 64upx;
		line-height: 64upx;
		font-size: 26upx;
		background-color: transparent;
	}

	.search-button {
		padding: 10rpx 30rpx 10rpx 30rpx;
	}

	.img-box {
		width: 200rpx !important;
		height: 200rpx !important;
	}

	.pay {
		padding: 10rpx 20rpx 10rpx 20rpx;
	}

	.button-bg {
		padding: 20rpx 40rpx 20rpx 40rpx;
	}

	.text-to-long {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}
</style>

<style scoped lang="scss">
	.send-title {
		color: #000;
		font-size: 36rpx;
		font-weight: bolder;
	}

	.send-limit {
		margin-top: 30rpx;
		font-size: 24rpx;
		color: #000;

		text {
			font-weight: bolder;
		}

		.send-time {
			color: #CD824A;
			margin-left: 10rpx;
		}
	}

	.send-line {
		width: 100%;
		height: 1px;
		background-color: #f5f5f5;
		margin-bottom: 20rpx;
		width: 710rpx;
		margin-left: 20rpx;
	}

	.send-line1 {
		width: 100%;
		height: 1px;
		background-color: #f5f5f5;
		margin-bottom: 20rpx;
		width: 710rpx;
		margin-top: 20rpx;
	}

	.send-address-info {
		color: #000;

		.sai-header {
			display: flex;
			flex-direction: row;
			font-weight: bolder;
			margin-bottom: 10rpx;

			.sai-phone {
				font-weight: normal;
				margin-left: 8rpx;
			}
		}

		.sai-detail {
			color: #000;
			font-size: 24rpx;
			margin-bottom: 20rpx;
			width: 690rpx;
			height: auto;

			image {
				vertical-align: text-bottom;
				margin-top: 20rpx;
				width: 30rpx;
				height: 30rpx;
			}
		}
	}
</style>